#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/11/8 9:37
# @Author  : TangZhongZheng
# @File    : player.py
# @Description :
import pygame

from src.timertask import TimerTask
from src.utils import import_folder


class Player(pygame.sprite.Sprite):
    def __init__(self, pos, *group):
        super().__init__(*group)

        # 人物运动状态动画
        self.animations = {}  # 人物动画
        self.import_assets()  # 初始化上述两个字典
        self.status = 'down'
        self.frame_index = 0
        self.image = self.animations[self.status][self.frame_index]
        self.rect = self.image.get_rect(center=pos)  # 设置位置

        # 运动属性
        self.direction = pygame.math.Vector2()
        self.speed = 200  # 人物运动速度
        self.pos = pygame.math.Vector2(self.rect.center)  # 位置的向量表达式

        # 按键锁
        self.timers = {
            'tool_use': TimerTask(350, self.use_tool),
            'tool_switch': TimerTask(200),
            'seed_use': TimerTask(350, self.use_seed),
            'seed_switch': TimerTask(200)
        }

        # 工具选取
        self.tools = ['hoe', 'axe', 'water']
        self.tool_index = 0
        self.selected_tool = self.tools[self.tool_index]

        # 种子使用
        self.seeds = ['tomato', 'corn']
        self.seed_index = 0
        self.selected_seed = self.seeds[self.seed_index]

    def input(self):
        # 获取全键盘状态
        keys = pygame.key.get_pressed()
        mouse = pygame.mouse.get_pressed()
        if not self.timers['tool_use'].active:
            # 方向移动
            if keys[pygame.K_UP] | keys[pygame.K_w]:
                self.direction.y = -1
                self.status = 'up'
            elif keys[pygame.K_DOWN] | keys[pygame.K_s]:
                self.direction.y = 1
                self.status = 'down'
            else:
                self.direction.y = 0

            if keys[pygame.K_LEFT] | keys[pygame.K_a]:
                self.direction.x = -1
                self.status = 'left'
            elif keys[pygame.K_RIGHT] | keys[pygame.K_d]:
                self.direction.x = 1
                self.status = 'right'
            else:
                self.direction.x = 0

            # 工具使用
            if mouse[pygame.BUTTON_LEFT - 1]:
                self.timers['tool_use'].activateTask()
                self.direction = pygame.math.Vector2()
                self.frame_index = 0
            # 工具切换
            if keys[pygame.K_q] and not self.timers['tool_switch'].active:
                self.timers['tool_switch'].activateTask()
                self.tool_index += 1
                self.tool_index = self.tool_index if self.tool_index < len(self.tools) else 0
                self.selected_tool = self.tools[self.tool_index]

            # 种子使用
            if mouse[pygame.BUTTON_RIGHT - 1]:
                self.timers['seed_use'].activateTask()
                self.direction = pygame.math.Vector2()
                self.frame_index = 0
            # 种子切换
            if keys[pygame.K_e] and not self.timers['seed_switch'].active:
                self.timers['seed_switch'].activateTask()
                self.seed_index += 1
                self.seed_index = self.seed_index if self.seed_index < len(self.seeds) else 0
                self.selected_seed = self.seeds[self.seed_index]

    def get_status(self):
        # 回归空闲状态
        if self.direction.length() == 0:
            self.status = self.status.split('_')[0] + '_idle'
        if self.timers['tool_use'].active:
            if self.selected_tool != '':
                self.status = self.status.split('_')[0] + "_" + self.selected_tool

    def update_timer(self):
        for timer in self.timers.values():
            if timer.active:
                timer.update()

    def move(self, dt):
        """
        人物的移动处理
        :param dt:
        :return:
        """
        if self.direction.magnitude() > 0:
            # pygame.math.Vector2.magnitude
            # returns the Euclidean magnitude of the vector.
            self.direction = self.direction.normalize()
            # pygame.math.Vector2.normalize
            # returns a vector with the same direction but length 1.
        # x轴
        self.pos.x += self.speed * self.direction.x * dt
        # y轴
        self.pos.y += self.speed * self.direction.y * dt
        self.rect.center = self.pos

    def animate(self, dt):
        """
        更新动画
        :param dt:
        :return:
        """
        self.frame_index += 4 * dt
        if self.frame_index >= len(self.animations[self.status]):
            self.frame_index = 0
        self.image = self.animations[self.status][int(self.frame_index)]

    def use_tool(self):
        print(self.selected_tool)
        pass

    def use_seed(self):
        print(self.selected_seed)
        pass

    def import_assets(self):
        """
        导入人物状态图片
        :return:
        """
        self.animations = {'up': [], 'down': [], 'left': [], 'right': [],
                           'up_idle': [], 'down_idle': [], 'left_idle': [], 'right_idle': [],
                           'up_hoe': [], 'down_hoe': [], 'left_hoe': [], 'right_hoe': [],
                           'up_axe': [], 'down_axe': [], 'left_axe': [], 'right_axe': [],
                           'up_water': [], 'down_water': [], 'left_water': [], 'right_water': []}
        path = '../resource/graphics/character'
        for animation in self.animations.keys():
            self.animations[animation] = import_folder(path + "/" + animation)

    def update(self, dt):
        self.input()
        self.get_status()
        self.update_timer()
        self.move(dt)
        self.animate(dt)
